#include "dfs.h"
#include <minix/com.h>
#include <minix/callnr.h>
#include <sys/wait.h>
#include "param.h"
#include "cache.h"

FORWARD _PROTOTYPE( int dfs_init, (void)				);
FORWARD _PROTOTYPE( void get_work, (void)				);
FORWARD _PROTOTYPE( void reply, (int whom,int result)	);

PUBLIC int main(void)
{
	int result;
	int step;
	
	/* call init function for DFS */
	step=0;
	result = dfs_init();
	if (result != OK) return (ERROR);
	
	while(TRUE){
		get_work();
		if (call_nr == SYN_ALARM) {
			result = SUSPEND;
		}
		/* If the system call number is valid, perform the call. */
		if ((unsigned) call_nr >= NCALLS) {
			result = ENOSYS;
		} else {
			result = (*call_vec[call_nr])();
		}
		if (result != SUSPEND) { reply(who_e, result); }
	}
	
	/* Destroy cache */
	destroy_cache();
	
	return OK;
}
/*===========================================================================*
 *				dfs_init				     *
 *===========================================================================*/
PRIVATE int dfs_init()
{	
	char *del; /*TEST!*/
	/* Initialization of the server occurs here */
	int i;
	
	/* Service not initialized in servers start */
	dfs_initialized = NOTINIT; 
	
	/* DFS components not yet initialized */
	dfs_net_pid = NOTSETCOMPONENT;
	
	/* initiate cache */
	init_cache();
	insert_to_cache("cached.txt",del);
	insert_to_cache("cached1.txt",del);
	insert_to_cache("cached.txt",del);
	return(OK);
}
/*===========================================================================*
 *				get_work				     *
 *===========================================================================*/
PRIVATE void get_work()
{
/* Wait for the next message and extract useful information from it. */
	if (receive(ANY, &m_in) != OK)
  		panic(__FILE__,"DFS receive error",NO_NUM);
	who_e = m_in.m_source;	/* who sent the message */
	call_nr = m_in.m_type;	/* system call number */
}

/*===========================================================================*
 * 				reply					     *
 *===========================================================================*/
PRIVATE void reply(whom,result)
int whom;		/* process to reply */
int result;		/* result of the call (usually ok or error ) */
{
	int s;
	m_out.reply_type = result;
	s = send(whom,&m_out);
	if (s != OK) panic(__FILE__,"DFS send error",NO_NUM);
}
